#include <Arduino.h>
#include <LedControl.h>
#include <DS3231.h>
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <MatrixClock.h>
#define DIO 12   //d6
#define Cs 13    //d7
#define Clk 15   //d8
#define max 4
const int delaytime = 500;
int connectingcount =0;   //用于开机wifi连接计时
//LedControl lc = LedControl(DIO, Clk, Cs, max);
MatrixClock mc =MatrixClock(DIO,Clk,Cs);
DS3231 myclock;   
RTClib RTC;    //ds3231采用默认i2c引脚
DateTime dt;

//WiFi部分对象定义 
const char * ssid = "ZNet";
const char * password = "5678ping";

//登录Ntp服务器，获取时间
WiFiUDP ntpUdp;
NTPClient timeClient(ntpUdp, "ntp1.aliyun.com",60*60*8, 30*60*1000);


void setup()
{
  // put your setup code here, to run once:
  mc.init();
  Wire.begin();
  Serial.begin(9600);

// matrixclock对象初始化
 // mc.init();
  

  //WiFi初始化
  WiFi.begin(ssid,password);
  mc.wifidot();
  delay(1000);
  Serial.print("WiFi connecting");
  while(WiFi.status() != WL_CONNECTED)
  {
    mc.wifidot();
    delay(500);
    Serial.print(".");
    connectingcount++;
    if(connectingcount>=30)
      break;
          
  }
  if(connectingcount>=30)
  {
    mc.wifinotconn();
    connectingcount = 0;
  }
  else
  {
    mc.wificonnected();
    connectingcount = 0;
  }
  timeClient.begin();  //ntp服务初始化
  delay(1000);
  timeClient.update(); //从ntp服务器获取时间
  
  //获取当前时间戳
  DateTime tt=DateTime(timeClient.getEpochTime());

  //mc对象滚动显示前初始化时间数组
  mc.timeinit(tt.hour(),tt.minute(),tt.second());

  //给ds3231设定时间
  myclock.setYear(tt.year()-2000);
  myclock.setMonth(tt.month());
  myclock.setDate(tt.day());
  myclock.setHour(tt.hour());
  myclock.setMinute(tt.minute());
  myclock.setSecond(tt.second());
  myclock.setDoW(tt.dayOfTheWeek());
  
  
}


void loop()
{
  // put your main code here, to run repeatedly:
  
  unsigned short int  year;
  byte month,day;
  timeClient.getDay(year,month,day);
  dt=RTC.now();
  
  //mc.RollMerge(dt.hour(),dt.minute(),dt.second(),false);
  //mc.Display();
  mc.testdisplay(dt.year(),dt.month(),dt.day(),dt.dayOfTheWeek(),dt.hour(),dt.minute(),dt.second(),false); 
 
  Serial.print(String(year)+"-"+String(month)+"-"+String(day));
  Serial.print("    ");
  Serial.print(dt.year());
  Serial.print("-");
  Serial.print(dt.month());
  Serial.print("-");
  Serial.print(dt.day());
  Serial.print("-");
  Serial.print(dt.dayOfTheWeek());
  Serial.print("  ");
  Serial.print(timeClient.getEpochTime());
  Serial.println();

}